package org.wordml.core.experiment.word2003;

import java.io.OutputStream;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.wordml.core.encoding.XmlEnconding;
import org.wordml.core.experiment.word2003.elements.WordProcessingException;

public class WordDocument {
	private MSWordNamespace namespace = MSWordNamespace.W;
	private XmlEnconding encoding;
	XMLStreamWriter writer;
	
	public WordDocument(OutputStream outstream, XmlEnconding encoding) throws WordProcessingException {
		this.encoding = encoding;
		XMLOutputFactory xof = XMLOutputFactory.newInstance();
		try {
			writer = xof.createXMLStreamWriter(outstream, encoding.getEncoding());
		} catch (XMLStreamException e) {
			throw new WordProcessingException("Error creating the StreamWriter ["+e.getMessage()+"]",e);
		}
	}

	public void write() throws WordProcessingException {
		try {
			writer.writeStartDocument(encoding.getEncoding(),"1.0");
			writer.writeProcessingInstruction("mso-application progid=\"Word.Document\"");
			writer.setPrefix(namespace.getPrefix(), namespace.getUri());
			writer.writeStartElement(namespace.getPrefix(),"wordDocument",namespace.getUri());
			for(MSWordNamespace wns :MSWordNamespace.values()){
				writer.writeNamespace(wns.getPrefix(), wns.getUri());
			}
			
			//-- Start Processing child nodes
			
			//TODO: HERE goes the document tree
			//TODO: Need to finish to define all Elements pertaining to a document
			//-- End processing child nodes
			
			writer.writeEndElement();
			writer.writeEndDocument();
			writer.flush();
		} catch(XMLStreamException exception){
			throw new WordProcessingException(exception);
		}
	}
}
